package org.coding.springbootdemoredisstandalone.rediscontroller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;

/**
 * @author guoxuehe
 * @date 2021/1/23 16:05
 * @desc
 **/
public class RedisTransactionOperation {

    @Autowired
    private RedisTemplate redisTemplate;

    public void transactionSet(Map<String, Object> commandList) {
        //1 开启事务权限
        redisTemplate.setEnableTransactionSupport(true);
        try {
            //2. 开启事务
            redisTemplate.multi();
            //3. 执行事务命令
            for (Map.Entry<String, Object> entry : commandList.entrySet()) {
                String mapKey = entry.getKey();
                Object mapValue = entry.getValue();

                redisTemplate.opsForValue().set(mapKey, mapValue);
            }
            // 4. 成功就提交
            redisTemplate.exec();
        } catch (Exception e) {
            //5. 失败就回滚
            redisTemplate.discard();
        }
    }
}
